package com.cccyy.generate.idcard;

import java.util.Random;

public class BankCardGenerator {

    public static void main(String[] args) {
        String cardNumber = generateCardNumber();
        System.out.println("生成的银行卡号: " + cardNumber);
    }

    public static String generateRandomNumber(int length) {
        Random random = new Random();
        StringBuilder number = new StringBuilder();

        for (int i = 0; i < length; i++) {
            number.append(random.nextInt(10));
        }

        return number.toString();
    }

    //使用Luhn算法计算校验位
    public static int calculateLuhnCheckDigit(String number) {
        int sum = 0;
        boolean alternate = false;

        for (int i = number.length() - 1; i >= 0; i--) {
            int n = Character.getNumericValue(number.charAt(i));

            if (alternate) {
                n *= 2;
                if (n > 9) {
                    n -= 9;
                }
            }
            sum += n;
            alternate = !alternate;
        }
        return (10 - (sum % 10)) % 10;
    }

    public static String generateCardNumber() {
        String randomNumbers = generateRandomNumber(15);
        int checkDigit = calculateLuhnCheckDigit(randomNumbers);
        return randomNumbers + checkDigit;
    }

}